<template>
  <div class="app-container">
    <el-divider>
      <div class="my-divider">基础信息</div>
    </el-divider>
    <el-form
      :model="form"
      ref="form"
      size="small"
      label-width="115px"
      label-position="left"
      :rules="rules"
    >
      <el-form-item label="工艺路线名称" prop="prouteName">
        <el-input v-model="form.prouteName" placeholder="请输入工艺路线名称" />
      </el-form-item>
      <el-form-item label="工艺路线说明" prop="prouteDetail" class="my-desc">
        <el-input v-model="form.prouteDetail"
                  :autosize="{ minRows: 3 }" type="textarea" placeholder="请输入说明"
        />
      </el-form-item>
      <el-form-item label="工艺路线备注" prop="prouteDesc" class="my-desc">
        <el-input v-model="form.prouteDesc"
                  :autosize="{ minRows: 3 }" type="textarea" placeholder="请输入备注"
        />
      </el-form-item>
    </el-form>

    <el-divider>
      <div class="my-divider">工序组成</div>
    </el-divider>
    <el-button type="primary" @click="handleToAddPProcedure">添加</el-button>
    <el-button type="primary" plain :disabled="!pProcedureRemoveList || pProcedureRemoveList.length === 0"
               @click="handleRemovePProcedure"
    >移除
    </el-button>
    <el-table :data="prouteProcedureList"
              @selection-change="selectChangeRemoveProcedure"
              :default-sort="{prop: 'ppSort', order: 'ascending'}"
              row-key="ppProcedureCode.value"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="工序编码" align="center" prop="ppProcedureCode" />
      <el-table-column label="工序名称" align="center" prop="ppProcedureName" />
      <el-table-column label="工序顺序" align="center" prop="ppSort" sortable />
      <el-table-column label="计价方式" align="center" prop="ppCalcType">
        <template slot-scope="scope">
          <dict-tag :options="getCalcSalType" :value="scope.row.ppCalcType" />
        </template>
      </el-table-column>
      <el-table-column label="计价单价" align="center" prop="ppCalcSingle" />
      <el-table-column label="是否为关键工序" align="center" prop="ppKey">
        <template slot-scope="scope">
          {{ scope.row.ppKey === '1' ? '是' : '否' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleToUpdateProcedure(scope.row, scope.$index)"
            v-hasPermi="['pbs:procedure:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDeleteProcedure(scope.$index)"
            v-hasPermi="['pbs:procedure:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-divider>
      <div class="my-divider">关联产品</div>
    </el-divider>
    <el-button type="primary" @click="handleToAddGood">
      添加
    </el-button>
    <el-button type="primary" plain :disabled="!goodRemoveList || goodRemoveList.length === 0"
               @click="handleRemoveGood"
    >移除
    </el-button>
    <el-table :data="gbsGoods"
              @selection-change="selectChangeRemoveGood"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="产品编号" align="center" prop="pdCode" />
      <el-table-column label="产品名称" align="center" prop="pdName" />
      <el-table-column label="规格型号" align="center" prop="pdSpecType" />
      <el-table-column label="单位" align="center" prop="gbsGoodUnit.guName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDeleteGood(scope.$index)"
            v-hasPermi="['pbs:procedure:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>


    <!--    底部或隐藏区域-->
    <!-- 上传按钮 -->
    <MyConfirmBtnGroup :after-cancel-open-page="backPage" :ok-event="submitForm" />

    <!--    工序添加和修改-->
    <el-dialog :title="procedureTitle" :visible.sync="procedureDialogVisible" width="50%" append-to-body
    >
      <el-form ref="procedureForm" :model="procedureForm" :rules="procedureRules" label-width="115px"
               label-position="left"
               class="my-dialog-form"
               size="small"
      >
        <el-form-item label="工序" prop="ppProcedureCode">
          <el-select
            v-model="procedureForm.ppProcedureCode"
            placeholder="请选择工序"
          >
            <el-option
              v-for="p in allProcedures"
              :key="p.procedureCode"
              :label="p.procedureName"
              :value="p.procedureCode"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="关键工序" prop="ppKey">
          <el-radio-group v-model="procedureForm.ppKey">
            <el-radio v-for="item in ppKeys" :key="item.id" :label="item.value">
              {{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="工序顺序" prop="ppSort">
          <el-input-number v-model="procedureForm.ppSort" />
        </el-form-item>
        <el-form-item label="计价方式" prop="ppCalcType">
          <el-select
            v-model="procedureForm.ppCalcType"
            placeholder="请选择计价方式"
            class="my-input"
          >
            <el-option
              v-for="dict in getCalcSalType"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="计价单价" prop="ppCalcSingle">
          <el-input-number v-model="procedureForm.ppCalcSingle" :precision="2" />
        </el-form-item>
        <el-form-item label="备注" prop="ppDesc" class="my-desc">
          <el-input
            type="textarea"
            :autosize="{ minRows: 3 }"
            placeholder="请输入备注"
            v-model="procedureForm.ppDesc"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="okProcedure">确 定</el-button>
        <el-button @click="cancelProcedure">取 消</el-button>
      </div>
    </el-dialog>

    <MyGoodDialog title="添加产品"
                  v-model="dialogTableVisible"
                  :goods.sync="gbsGoods"
                  :showTabs="false"
                  :single-mode="false"
                  :list-data="noRouteGoods"
                  :enable-data="true"
    />
  </div>
</template>

<script>
import MyConfirmBtnGroup from '@/components/MyConfirmBtnGroup/index.vue'
import MyGoodDialog from '@/components/MyGoodDialog/index.vue'
import { allProcedure } from '@/api/yyj/pbs/procedure'
import { noRouteGood } from '@/api/yyj/gbs/good'
import { addProcedureRoute, getProcedureRoute, updateProcedureRoute } from '@/api/yyj/pbs/procedureRoute'

export default {
  name: 'Change',
  dicts: ['yyj_common_status', 'pbs_calc_sal'],
  components: { MyGoodDialog, MyConfirmBtnGroup },
  data() {
    return {
      backPage: '/pbs/procedureRoute',
      procedureTitle: '',
      // 工序对话框状态
      procedureDialogVisible: false,
      // 产品对话框状态
      dialogTableVisible: false,
      // 表单参数
      form: {
        prouteStatus: '1'
      },
      // 表单校验
      rules: {
        prouteName: [
          { required: true, message: '工艺路线名称不能为空', trigger: 'blur' }
        ],
        prouteStatus: [
          { required: true, message: '状态不能为空', trigger: 'change' }
        ]
      },
      ppKeys: [
        {
          id: 1,
          label: '是',
          value: '1'
        },
        {
          id: 0,
          label: '否',
          value: '0'
        }
      ],
      // 所有工序
      allProcedures: [],
      // 所有备用工序
      bakProcedures: [],
      // 工序表单
      procedureForm: {
        currentIndex: null,
        ppKey: '0',
        ppCalcSingle: 0
      },
      // 工序校验规则
      procedureRules: {
        ppProcedureCode: [{ required: true, message: '工序不为空', trigger: 'change' }],
        ppCalcType: [{
          required: true, message: '计价方式不为空', trigger: 'change'
        }],
        ppCalcSingle: [{
          required: true, message: '计件单价不为空', trigger: 'change'
        }]
      },
      // 添加的工序
      prouteProcedureList: [],
      // 移除的工序
      pProcedureRemoveList: [],
      // 添加的产品
      gbsGoods: [],
      // 移除的产品
      goodRemoveList: [],
      // 本地数据
      noRouteGoods: [],
      backGoods: [],
      // 修改数据
      removeGoods: []
    }
  },
  computed: {
    getStatus() {
      return this.dict.type.yyj_common_status
    },
    getCalcSalType() {
      return this.dict.type.pbs_calc_sal
    }
  },
  created() {
    const prouteCode = this.$route.params && this.$route.params.prouteCode
    if (prouteCode) {
      this.getProcedureRoute(prouteCode)
    }
  },
  methods: {
    // 获取详情
    async getProcedureRoute(prouteCode) {
      const res = await getProcedureRoute(prouteCode)
      this.form = res.data
      this.gbsGoods = res.goods
      this.backGoods = res.goods
      this.prouteProcedureList = res.pbsProuteProcedures
    },
    // 获取所有工序
    async getAllProcedures() {
      const res = await allProcedure({ procedureStatus: 1 })
      this.allProcedures = res.data
      this.bakProcedures = res.data
      if (this.prouteProcedureList && this.prouteProcedureList.length > 0) {
        this.prouteProcedureList.forEach(e1 => {
          this.allProcedures = this.allProcedures.filter(e2 => e2.procedureCode !== e1.ppProcedureCode)
        })
      }
    },
    // 去添加工序
    async handleToAddPProcedure() {
      this.resetProcedureForm()
      await this.getAllProcedures()
      this.procedureForm.currentIndex = null
      this.procedureTitle = '添加工序'
      this.procedureDialogVisible = true
    },
    // 去修改工序
    async handleToUpdateProcedure(row, index) {
      this.resetProcedureForm()
      await this.getAllProcedures()
      this.allProcedures.unshift({
        procedureCode: row.ppProcedureCode,
        procedureName: row.ppProcedureName
      })
      this.procedureForm = { ...row }
      this.procedureForm.currentIndex = index
      this.procedureTitle = '修改工序'
      this.procedureDialogVisible = true
    },
    // 工序选项改变
    selectChangeRemoveProcedure(selection) {
      this.pProcedureRemoveList = selection
    },
    // 移除工序 主图标
    handleRemovePProcedure() {
      this.pProcedureRemoveList.forEach(e1 => {
          this.prouteProcedureList =
            this.prouteProcedureList.filter(e2 => e2.ppProcedureCode !== e1.ppProcedureCode)
        }
      )
    },
    // 移除工序
    handleDeleteProcedure(index) {
      this.prouteProcedureList.splice(index, 1)
      this.$modal.msgSuccess('删除成功')
    },
    // 确认修改或添加工序
    okProcedure() {
      this.$refs['procedureForm'].validate(valid => {
        if (valid) {
          if (this.procedureForm.currentIndex === null
            || this.procedureForm.currentIndex === ''
            || this.procedureForm.currentIndex < 0) {
            // 添加
            this.$modal.msgSuccess('添加成功')
            this.procedureForm.ppProcedureName = this.getProcedureName(this.procedureForm.ppProcedureCode)
            this.prouteProcedureList.push({ ...this.procedureForm })
            this.procedureDialogVisible = false
          } else {
            // 修改
            this.$modal.msgSuccess('修改成功')
            // 替换
            this.procedureForm.ppProcedureName = this.getProcedureName(this.procedureForm.ppProcedureCode)
            this.prouteProcedureList.splice(this.procedureForm.currentIndex, 1, { ...this.procedureForm })
            this.procedureDialogVisible = false
          }
        }
      })
    },
    // 取消修改或添加工序
    cancelProcedure() {
      this.resetProcedureForm()
      this.procedureDialogVisible = false
    },
    // 工序重置数据
    resetProcedureForm() {
      this.procedureForm = {
        ppKey: '0',
        ppSort: 0,
        ppCalcSingle: 0
      }
      this.resetForm('procedureForm')
    },
    // 添加产品
    async handleToAddGood() {
      await this.getNoRouteGoods()
      this.noRouteGoods.push(...this.backGoods)
      this.dialogTableVisible = true
    },
    // 获取没有工艺路线的产品
    async getNoRouteGoods() {
      const res = await noRouteGood()
      console.log(res)
      this.noRouteGoods = res.data
    },
    // 移除产品
    handleRemoveGood() {
      this.goodRemoveList.forEach(e1 => {
          this.gbsGoods =
            this.gbsGoods.filter(e2 => {
              if (e2.pdCode !== e1.pdCode) {
                return true
              }
              this.removeGoods.push({ ...e2 })
              return false
            })
        }
      )
    },
    selectChangeRemoveGood(selection) {
      this.goodRemoveList = selection
    },
    handleDeleteGood(index) {
      const good = this.gbsGoods.splice(index, 1)
      this.removeGoods.push(...good)
      this.$modal.msgSuccess('删除成功')
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(async valid => {
        if (valid) {
          this.$modal.loading('正在提交...')
          if (this.$route.params && this.$route.params.prouteCode) {
            await updateProcedureRoute({
              pbsProcedureRoute: this.form,
              pbsProuteProcedureList: this.prouteProcedureList,
              gbsGoodList: this.gbsGoods,
              removeGoodList: this.removeGoods
            })
            this.$modal.msgSuccess('修改成功')
          } else {
            await addProcedureRoute({
              pbsProcedureRoute: this.form,
              pbsProuteProcedureList: this.prouteProcedureList,
              gbsGoodList: this.gbsGoods
            })
            this.$modal.msgSuccess('新增成功')
          }
          this.afterSubmit()
        }
      })
    },
    // 重置
    reset() {
      this.form = {}
      this.resetForm('form')
    },
    afterSubmit() {
      this.$tab.closeOpenPage()
      this.reset()
      this.$tab.refreshPage({
        path: this.backPage
      })
      this.$modal.closeLoading()
    },
    // 将工序编号转为 名称
    getProcedureName(pCode) {
      return this.bakProcedures.find(e => e.procedureCode === pCode).procedureName
    }
  }
}
</script>

<style scoped lang="scss">
@import '@/assets/styles/yyj/change';

.el-dialog .el-form-item {
  width: 50%;
  padding-left: 5% !important;
}
</style>
